<script lang="ts" setup>
import { onBeforeUnmount, computed } from 'vue';
import {
  alert,
  clearAllAlerts,
  confirm,
  Page,
  prompt,
  useVbenModal,
} from '@vben/common-ui';
import { Button, Card, Flex, message } from 'ant-design-vue';
import FormModalDemo from './form-modal-demo.vue';
import { useUserStore } from '#/store/user'

const userStore = useUserStore()

const handleIncrementAge = (index: number) => {
  userStore.incrementAge(index)
}
const userId = computed(() => userStore.userId);

defineOptions({ name: 'ModalExample' });

interface User {
  name: string;
  age: number;
  email?: string;
  id?: string;
}

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const editUser = (user: User) => {
  formModalApi
    .setData({
      values: { name: user.name, age: user.age, email: user.email },
      isAdd: false // 设置为编辑模式
    })
    .open();
  userStore.editUserId(user.id)
}

const addUser = () => {
  formModalApi
    .setData({
      values: { name: '', age: '', email: '' }, // 空值用于添加
      isAdd: true // 设置为添加模式
    })
    .open();
  userStore.editUserId('') // 清空编辑ID
}
const delUser = (id:string) => {
   confirm(`确定要删除用户ID为${id}的用户吗？`)
    .then(() => {
      userStore.deleteUser(id)
    })
    .catch(() => {
      message.warning('取消删除');
    });
  console.log(id)
 
}
function openFormModal(user?: User) {
  if (user) {
    editUser(user);
  } else {
    addUser();
  }
}
</script>

<template>
  <Page
    auto-content-height
    description="弹窗组件常用于在不离开当前页面的情况下，显示额外的信息、表单或操作提示，更多api请查看组件文档。"
    title="弹窗组件示例"
  >
    <template #extra>
      <DocButton path="/components/common-ui/vben-modal" />
    </template>

    <FormModal />

    <Flex wrap="wrap" class="w-full" gap="10">
      <Card class="w-[300px]" title="表单弹窗示例">
        <p>弹窗与表单结合</p>
        <template #actions>
          <Button type="primary" @click="addUser"> 添加用户 </Button>
        </template>
      </Card>
      <div class="section">
        <h3>用户列表 (来自 Pinia)</h3>
        <ul class="user-list">
          <li v-for="(user, index) in userStore.users" :key="index">
            <span class="user-name">{{ user.name }} ------  </span>  
            <span class="user-age" @click="handleIncrementAge(index)">
              年龄: {{ user.age }} (点击+1)
            </span>
              <span class="user-age" >
              --------邮箱: {{ user.email }} -------
            </span>
            <span>id:{{userId}}</span>----
            <span @click="editUser(user)">编辑</span>----
            <span @click = delUser(user.id)>删除</span>
          </li>
        </ul>
      </div>
    </Flex>
  </Page>
</template>
